using System.Collections;
using System.Collections.Generic;
using System.Linq;
using QAssetBundle;
using UnityEngine;
using QFramework;

namespace ProjectSurvivor
{
	public partial class GetAllExp : GamePlayObject
	{
		static IEnumerator FlyToPlayStart()
		{
			IEnumerable<PowerUp> exps = FindObjectsByType<Exp>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
			IEnumerable<PowerUp> coins = FindObjectsByType<Coin>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
			exps.Concat(coins);

			int count = 0;
			
			// 获取所有经验值、金币
			foreach (Exp exp in exps.OrderByDescending(e => e.InScreen)
				         .ThenBy(e => Player.Default.Distance2D(e)))
			{
				if (!exp.InScreen && count > 5)
				{
					count = 0;
					yield return new WaitForEndOfFrame();
				}
				else if(exp.InScreen && count > 15)
				{
					count = 0;
					yield return new WaitForEndOfFrame();
				}
				
				count++;
				ActionKit.OnUpdate.Register(() =>
				{
					if (Player.Default)
					{
						Vector3 direction = Player.Default.Direction2DFrom(exp);
						exp.transform.Translate(Time.deltaTime * 5f * direction);
					}
				}).UnRegisterWhenGameObjectDestroyed(exp);
				
			}
		}
		
		private void OnTriggerEnter2D(Collider2D other)
		{
			if (other.GetComponent<CollectibleArea>())
			{
				PowerUpManager.Default.StartCoroutine(FlyToPlayStart());

				AudioKit.PlaySound(Sfx.GETALLEXP);
				this.DestroyGameObjGracefully();
			}
		}

		protected override Collider2D collider2d => SelfCircleCollider2D;
	}
}
